package com.uinnova.product.eam.service.utils;

import lombok.extern.slf4j.Slf4j;
import net.dreamlu.mica.xss.core.XssType;
import net.dreamlu.mica.xss.utils.XssUtil;
import org.apache.commons.lang.StringEscapeUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Entities;

/**
 * @Filename: XssClean
 * @Author: WangBaoDe
 * @Data:2024/5/21 14:54
 */

@Slf4j
public class XssCleanerUtil implements net.dreamlu.mica.xss.core.XssCleaner {

    public static final XssUtil.HtmlSafeList WHITE_LIST = new XssUtil.HtmlSafeList();

    @Override
    public String clean(String s, String s1, XssType xssType) {
        Document.OutputSettings settings = new Document.OutputSettings()
                // 1. 转义用最少的规则，没找到关闭的方法
                .escapeMode(Entities.EscapeMode.xhtml)
                // 2. 保留换行
                .prettyPrint(false);
        //对富文本内容进行转义
        log.debug("对富文本内容转义: " + s1);
        s1 = StringEscapeUtils.unescapeHtml(s1);
        log.debug("转义结果: " + s1);
        // 注意会被转义
        String escapedText = Jsoup.clean(s1, "",WHITE_LIST, settings);
        log.info("处理结果: " + escapedText);
        // 3. 反转义
        return Entities.unescape(escapedText);
    }

    @Override
    public String clean(String html, XssType xssType) {
        Document.OutputSettings settings = new Document.OutputSettings()
                // 1. 转义用最少的规则，没找到关闭的方法
                .escapeMode(Entities.EscapeMode.xhtml)
                // 2. 保留换行
                .prettyPrint(false);
        //对富文本内容进行转义
        log.info("clean 对富文本内容转义: " + html);
        html = StringEscapeUtils.unescapeHtml(html);
        log.info("clean 转义结果: " + html);
        // 注意会被转义
        String escapedText = Jsoup.clean(html, "",WHITE_LIST, settings);
        log.info("clean 处理结果: " + escapedText);
        // 3. 反转义
        return Entities.unescape(escapedText);
    }
}
